package top.jfunc.common.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.jfunc.common.utils.ArrayUtil;
import top.jfunc.common.utils.StrUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author weihainan.
 * @since 0.1 created on 2017/2/23.
 */
public class BodyMultiReadFilter implements Filter {
	private static final Logger logger = LoggerFactory.getLogger(BodyMultiReadFilter.class);

	public static final String SKIP_URIS = "skipUris";
	public static final String SUPPORT_MULTI_VALUE = "supportMultiValue";
	private String[] skipUriArray = {};
	private boolean supportMultiValue = false;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String skipUris = filterConfig.getInitParameter(SKIP_URIS);
		if (StrUtil.isNotEmpty(skipUris)) {
			skipUriArray = skipUris.split(",");
		}
		String supportMultiValue = filterConfig.getInitParameter(SUPPORT_MULTI_VALUE);
		if(StrUtil.isNotEmpty(supportMultiValue)){
			this.supportMultiValue = Boolean.parseBoolean(supportMultiValue);
		}
		logger.info("{} init successfully,supportMultiValue:{}, skipUris:{}", getClass().getName(), this.supportMultiValue, skipUris);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
					throws IOException, ServletException {

		ServletRequest requestWrapper = null;
		if (request instanceof HttpServletRequest) {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			//post并且不是文件上传
			if(RequestParamUtil.isPost(httpServletRequest)
					&& !RequestParamUtil.isMultiPartRequest(httpServletRequest)){
				if(ArrayUtil.contains(skipUriArray, RequestParamUtil.requestUri(httpServletRequest))){
					//这个接口比较特殊，是post，但是其数据又在query参数上
				}else {
					requestWrapper = new MultiReadHttpServletRequest(httpServletRequest, supportMultiValue);
				}
			}
		}

		chain.doFilter(null == requestWrapper ? request : requestWrapper, response);
	}

	@Override
	public void destroy() {

	}
}